package com.shop.autoshop.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shop.autoshop.pojo.Product;
import com.shop.autoshop.pojo.User;
import com.shop.autoshop.service.OrderService;
import com.shop.autoshop.service.ProductService;
import com.shop.autoshop.service.UserService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping("/ajax")
public class AjaxController {
    private Log log = LogFactory.getLog(getClass());
    @Autowired
    private UserService userService;
    @Autowired
    private ProductService productService;
    @Autowired
    private OrderService orderService;

    @ResponseBody
    @PostMapping("/LoginVf")
    public String LoginVf(String ticket, String randstr, HttpServletRequest req, HttpSession httpSession){
        String aid = "2083729790";  //Aid
        String AppSecretKey = "0TlV8i_2MEsIRJAF2WIxzVQ**"; //AppKey
        String vfurl = "https://ssl.captcha.qq.com/ticket/verify";
        String userIp = req.getRemoteAddr();
        if(userIp.equals("127.0.0.1") || userIp.equals("0:0:0:0:0:0:0:1")){
            //根据网卡取本机配置的IP
            InetAddress inet=null;
            try {
                inet = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            userIp = inet.getHostAddress();
        }
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet;
        CloseableHttpResponse response = null;
        try {
            httpGet = new HttpGet(vfurl+"?aid="+aid+"&AppSecretKey="+AppSecretKey+"&Ticket="+URLEncoder.encode(ticket, "UTF-8")+"&Randstr="+URLEncoder.encode(randstr, "UTF-8")+"&UserIP="+URLEncoder.encode(userIp, "UTF-8"));
            response = httpclient.execute(httpGet);

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String res = EntityUtils.toString(entity);
                System.out.println(res); // 临时输出
                //System.out.println(vfurl+"?aid="+aid+"&AppSecretKey="+AppSecretKey+"&Ticket="+URLEncoder.encode(ticket, "UTF-8")+"&Randstr="+URLEncoder.encode(randstr, "UTF-8")+"&UserIP="+URLEncoder.encode(userIp, "UTF-8"));

                JSONObject result = JSON.parseObject(res);
                // 返回码
                int code = result.getInteger("response");
                // 恶意等级
                int evilLevel = result.getInteger("evil_level");

                if(evilLevel > 60){
                    log.warn("验证操作危险数较高,IP:"+userIp);
                }

                // 验证成功
                if (code == 1){
                    httpSession.setAttribute("loginVfCode",1);
                    return "1";
                }
            }
        } catch (java.io.IOException e) {
            // 忽略
        } finally {
            try {
                response.close();
            } catch (Exception ignore) {
            }
        }


        return "-1";
    }
    @PostMapping("/Login")
    @ResponseBody
        public String Login(String userName,String userPass,HttpSession httpSession){
        Integer loginVfCode =  (Integer) httpSession.getAttribute("loginVfCode");
        //System.out.println(loginVfCode);
        if(loginVfCode == null || loginVfCode != 1){
            return "-2";
        }
        User user = userService.getUserByName(userName);
        if(user == null){
            httpSession.setAttribute("loginVfCode",0);
            return "-1";
        }else{
            String encodeStr= DigestUtils.md5DigestAsHex(userPass.getBytes());
            //System.out.println(encodeStr);
            if(encodeStr.equalsIgnoreCase(user.getUserPassword())){
                httpSession.setAttribute("USER",user);
                httpSession.setAttribute("loginVfCode",0);
                return "1";
            }
        }
        httpSession.setAttribute("loginVfCode",0);
        return "-3";
    }

    @PostMapping("/QueryVf")
    @ResponseBody
    public String QueryVf(String ticket, String randstr, HttpServletRequest req, HttpSession httpSession){
        String aid = "2083729790";
        String AppSecretKey = "0TlV8i_2MEsIRJAF2WIxzVQ**";
        String vfurl = "https://ssl.captcha.qq.com/ticket/verify";
        String userIp = req.getRemoteAddr();
        if(userIp.equals("127.0.0.1") || userIp.equals("0:0:0:0:0:0:0:1")){
            //根据网卡取本机配置的IP
            InetAddress inet=null;
            try {
                inet = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            userIp = inet.getHostAddress();
        }
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet;
        CloseableHttpResponse response = null;
        try {
            httpGet = new HttpGet(vfurl+"?aid="+aid+"&AppSecretKey="+AppSecretKey+"&Ticket="+URLEncoder.encode(ticket, "UTF-8")+"&Randstr="+URLEncoder.encode(randstr, "UTF-8")+"&UserIP="+URLEncoder.encode(userIp, "UTF-8"));
            response = httpclient.execute(httpGet);

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String res = EntityUtils.toString(entity);
                System.out.println(res); // 临时输出
                //System.out.println(vfurl+"?aid="+aid+"&AppSecretKey="+AppSecretKey+"&Ticket="+URLEncoder.encode(ticket, "UTF-8")+"&Randstr="+URLEncoder.encode(randstr, "UTF-8")+"&UserIP="+URLEncoder.encode(userIp, "UTF-8"));

                JSONObject result = JSON.parseObject(res);
                // 返回码
                int code = result.getInteger("response");
                // 恶意等级
                int evilLevel = result.getInteger("evil_level");

                if(evilLevel > 60){
                    log.warn("验证操作危险数较高,IP:"+userIp);
                }

                // 验证成功
                if (code == 1){
                    httpSession.setAttribute("queryVfCode",1);
                    return "1";
                }
            }
        } catch (java.io.IOException e) {
            // 忽略
        } finally {
            try {
                response.close();
            } catch (Exception ignore) {
            }
        }


        return "-1";
    }


}
